// model_holder.js



function isHandlerForEvent(event, h) {

    if (event == null || h == null) { return false }

    if (event.action != h.action) { return false }

    let accept = h.accept;
    if (accept != null) {
        if (!accept(event)) { return false }
    }

    return true
}

////////////////////////////////////////////////////////////////////////////////

function Chain(actionEvent) {
    this.event = actionEvent
    this.handlers = []
}

Chain.prototype = {

    Handle(p, fn) {
        let action = p.action;
        let accept = p.accept;
        let h = { action, accept, fn }
        this.handlers.push(h)
    },

    Finally(fn) {
        let event = this.event;
        let hlist = this.handlers;
        for (let i in hlist) {
            let h = hlist[i]
            if (isHandlerForEvent(event, h)) {
                return h.fn(event)
            }
        }
        fn(event)
    },

}


////////////////////////////////////////////////////////////////////////////////


function NewChain(actionEvent) {
    return new Chain(actionEvent)
}


export default {
    name: "action-handler-chain",
    New: NewChain,
}
